package co.za.itweb.defenceweb;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint({ "SetJavaScriptEnabled", "WorldReadableFiles" })
public class SingleFavorite extends FragmentActivity {
	public int TWITTER_AUTH;
	public Twitter mTwitter;
	public RequestToken mRequestToken;

	public String accessToken;
	public String accessTokenSecret;

	public boolean haveConnectedWifi;
	public boolean haveConnectedMobile;
	public double x;
	static ImageButton tweetB;
	protected static final String PREFS_NAME = "FAVORITES";

	private Integer newsValue;

	String title;

	int fontsize;
	public static int screenWidth;
	public static int screenHeight;
	public static ImageLoader imageLoader;

	Dialog dialog;
	Dialog emaildialog;

	ArrayAdapter<String> favorites;

	
	TextView text;
	Banner myFragmentBanner;
	Disquss myFragmentDisquss;
	TweetTask tt;
	ResumeTask rt;
	UpdateTask ut;
	String oauthVerifier;
	private Integer feedValue;
	private String density2;
	
	private int width;
	private View myWebView;
	private int bannerHolderWidth2;

	public void onCreate(Bundle icecream) {
		super.onCreate(icecream);
		setContentView(R.layout.onenews);

		Bundle extras = getIntent().getExtras();
		 feedValue = extras.getInt("feedid");

		newsValue = extras.getInt("id");
		if(feedValue==null || newsValue==null){
			SingleFavorite.this.finish();
		}
		// View vi = inflater.inflate(R.layout.onenews, null);

		if (feedValue == 0) {
			title = "Favorites";
		}
		

		LinearLayout layout = (LinearLayout) findViewById(R.id.cell3);
		 int colors[] =  {Color.parseColor("#FF4a79bc"),Color.parseColor("#FF33558d")};
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
				colors);
		layout.setBackgroundDrawable(grad);

TextView editorial = (TextView) findViewById(R.id.editorial);
		
		
		if(FirstScreen.fList
						.get(feedValue)._itemlist.get(newsValue).getEditorialContacts()
						.toString().length()>3){
		String[] editorialString = FirstScreen.fList
				.get(feedValue)._itemlist.get(newsValue).getEditorialContacts()
				.toString().split("##");
		 
		
		String companynamestring="";
		String emailstring="";
		String namestr="";
		String phone="";
		String position="";
		String issued="";
		String premail="";
		String prname="";
		String prphone="";
		
		
		String[] editorialItems1=editorialString[0].split("\\|");
		String[] editorialItems2=editorialString[1].split("\\|");
		String[] company = new String[2];
		String[] companycontact = new String[2];
		String[] companyname = new String[2];
		String[] companyphone = new String[2];
		String[] companyposition = new String[2];
		String[] IssuedBy = new String[2];
		String[] prEmail = new String[2];
		String[] prName = new String[2];
		String[] prPhone = new String[2];
		for(int g=0;g<editorialItems1.length;g++){
			if(g==0){
				company=editorialItems1[0].split("\\::");
				if(company.length==2){
					companynamestring="<b>"+company[1]+"</b><br /><br />";
				}
			}else if(g==1){
					companycontact=editorialItems1[1].split("\\::");
		        if(companycontact.length==2){
		        	emailstring=companycontact[1]+"<br />";
		        	
		        }
			   }else if(g==2){
				   		companyname=editorialItems1[2].split("\\::");
				   if(companyname.length==2){
					   namestr=companyname[1]+"<br />";
				   }
					} else if(g==3){
						 companyphone=editorialItems1[3].split("\\::");
						 if(companyphone.length==2){
							 phone=companyphone[1]+"<br />";
						 }
							}  else if(g==4){
								 companyposition=editorialItems1[4].split("\\::");
								 if(companyposition.length==2){
									 position= companyposition[1]+"<br /><br />";
								 }
								
									} 
		
		
		
		}
		
		for(int g=0;g<editorialItems2.length;g++){
			if(g==0){
				IssuedBy=editorialItems2[0].split("\\::");
				if(IssuedBy.length==2){
					issued=  "<br /><b>"+IssuedBy[1]+"</b><br />";
				}else if(g==1){
					prEmail=editorialItems2[1].split("\\::");
					if(prEmail.length==2){
						premail=prEmail[1]+"<br />";
					}
				}else if(g==2){
					prName=editorialItems2[2].split("\\::");
					if(prName.length==2){
						prname= prName[1]+"<br />";
					}
				}
				
				else if(g==3){
					prPhone=editorialItems2[3].split("\\::");
					if(prPhone.length==2){
						prphone=prPhone[1]+"<br />";
					}
				}
			}
		
		
		
		}
		
		String editorialFinal= companynamestring+emailstring+namestr+phone+position+issued+prname+premail+prphone;
		    
		editorial.setText(Html.fromHtml(editorialFinal));
		editorial.setBackgroundColor(Color.parseColor("#ffa6aeb6"));
		
		}//editorial
		
		 Bundle args = new Bundle();
		  args.putString("articleID",FirstScreen.fList.get(feedValue)._itemlist
					.get(newsValue).getId().toString());
		  args.putString("articleTITLE",FirstScreen.fList.get(feedValue)._itemlist
					.get(newsValue).getTitle().toString());
		 
		  Bundle args2 = new Bundle();
		  args2.putString("catID",FirstScreen.fList.get(feedValue)._itemlist
					.get(newsValue).getCategory().toString());
		myFragmentBanner = new Banner();
		myFragmentBanner.setArguments(args2);
		getSupportFragmentManager().beginTransaction()
				.add(R.id.fragmentbanner, myFragmentBanner).commit();
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);

	
		
		 width = metrics.widthPixels;
		 if(FirstScreen.fList.get(feedValue)._itemlist.get(newsValue).getId().length()>6){
				
				RelativeLayout linLayout = (RelativeLayout) findViewById(R.id.youtube);
				RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
				

				 myWebView = new WebView(SingleFavorite.this); 
				linLayout.addView(myWebView, layoutParams);
				
				

				 ((WebView) myWebView).getSettings().setJavaScriptEnabled(true);

		        ((WebView) myWebView).loadUrl("http://www.youtube.com/watch?v="+FirstScreen.fList.get(feedValue)._itemlist.get(newsValue).getId().toString()); 
		        
		        
				
				}else{
//					
//					RelativeLayout linLayout = (RelativeLayout) findViewById(R.id.disquss);
//					
//					if(determineDensity()=="ldpi"){
//						bannerHolderWidth2=(int) (int) (width+(width/3))-10;
//					}else if(determineDensity()=="mdpi"){
//						bannerHolderWidth2=(int) (width)-10;
//					}else if(determineDensity()=="hdpi"){
//						
//						bannerHolderWidth2=(int)  (width-(width/3))-10;
//						
//					}else if(determineDensity()=="xdpi"){
//						bannerHolderWidth2=(int)width+(width/2)-10;
//					}
//					RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(width,LayoutParams.WRAP_CONTENT);
//					
//
//					 myWebView = new WebView(SingleFavorite.this); 
//					linLayout.addView(myWebView, layoutParams);
//					
//				String articleID =FirstScreen.fList.get(feedValue)._itemlist.get(newsValue).getId().toString();
//				String articleTITLE =FirstScreen.fList.get(feedValue)._itemlist.get(newsValue).getTitle().toString();
//				
//				
//			
//				
//
//					((WebView) myWebView).getSettings().setJavaScriptEnabled(true);
//
//					int currentapiVersion = Build.VERSION.SDK_INT;
//					if (currentapiVersion <= Build.VERSION_CODES.GINGERBREAD){
//						System.out.println("Verzija: "+currentapiVersion);
//					((WebView) myWebView).setWebViewClient(new WebViewClient() {
//
//					}); 
//					((WebView) myWebView).setWebChromeClient(new WebChromeClient() {
//							@Override
//							public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
//								Toast.makeText(getApplicationContext(), message,Toast.LENGTH_SHORT).show();
//								  result.confirm();
//								  return true;
//						       }
//					 });
//					
//					 ((WebView) myWebView).loadData("<html><head><meta name=\"viewport\" content=\"minimum-scale=1.0; maximum-scale=1.0; user-scalable=false; initial-scale=1.0;\"/><style>html,body,iframe{margin:0;padding:0;}</style></head><body><iframe style=\"width:"+bannerHolderWidth2+"px;height:600px;border:0px;margin:0px;\" src=\"http://itweb.mobi/disqus-comments.php?id="+articleID+"&url=source=android&tag=article&id="+articleID+"&title="+articleTITLE+"\"></iframe></body></html>", "text/html", null);
//
//					
//					}else{
//						System.out.println("Verzija TREBALO BI : "+currentapiVersion);
//						((WebView) myWebView).setWebViewClient(new WebViewClient() {
//						
//							
//						}); 
//						((WebView) myWebView).setWebChromeClient(new WebChromeClient() {
//							@Override
//							public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
//								Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
//								  result.confirm();
//								  return true;
//						       }
//					 });
//					
//						 ((WebView) myWebView).loadUrl("http://itweb.mobi/disqus-comments.php?id="+articleID+"&url=source=android&tag=article&id="+articleID+"&title="+articleTITLE);
//						 
//						
//					}
//					


				}

		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(SingleFavorite.this);
		accessToken = settings.getString("twitter_access_token", null);
		accessTokenSecret = settings.getString("twitter_access_token_secret",
				null);
		tweetB = (ImageButton) findViewById(R.id.tweet_button);
		tt = new TweetTask(this);
		rt = new ResumeTask();
		ut = new UpdateTask(this);

		tweetB.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				tweetB.setBackgroundResource(R.drawable.twitter_visited);
				tweetB.setClickable(false);
				if (accessToken == null || accessToken.length() < 2) {
					tt.execute();

				} else {

					ut.execute();

				}

			}
		});

		TextView titletext = (TextView) findViewById(R.id.title);
		titletext.setText(title + " article");

		ImageButton back = (ImageButton) layout.findViewById(R.id.back);
	
		ImageButton info = (ImageButton) layout.findViewById(R.id.info);

		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent1 = new Intent(SingleFavorite.this, FirstScreen.class);
				intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent1);
				finish();
			}
		});

		info.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				Intent intent = new Intent(SingleFavorite.this,
						DialogActivity.class);
				startActivity(intent);

			}
		});

		text = (TextView) findViewById(R.id.textarticle);
		final TextView summary = (TextView) findViewById(R.id.summary);
		
		TextView author = (TextView) findViewById(R.id.author);
		TextView published = (TextView) findViewById(R.id.published);
		ImageView image = (ImageView) findViewById(R.id.bigimage);

		imageLoader = new ImageLoader(this.getApplicationContext());
		imageLoader.DisplayImage(
				FirstScreen.FavoriteList.get(feedValue)._itemlist.get(
						newsValue).getbigImage(), image);
		summary.setText(FirstScreen.FavoriteList
				.get(feedValue)._itemlist.get(newsValue).getSummary()
				.toString()+FirstScreen.FavoriteList
				.get(feedValue)._itemlist.get(newsValue).getStory()
				.toString());//Html.fromHtml
		summary.setMovementMethod(LinkMovementMethod.getInstance());
		
		text.setText(FirstScreen.FavoriteList.get(feedValue)._itemlist
				.get(newsValue).getTitle());
		if(FirstScreen.FavoriteList.get(feedValue)._itemlist.get(
				newsValue).getAuthor().length()>3){
		author.setText("By: "
				+ FirstScreen.FavoriteList.get(feedValue)._itemlist.get(
						newsValue).getAuthor());
		}
		if (FirstScreen.FavoriteList.get(feedValue)._itemlist
				.get(newsValue).getpubDate().length() > 17) {
			published
					.setText(FirstScreen.FavoriteList.get(feedValue)._itemlist
							.get(newsValue).getpubDate().substring(0, 17));
		} else {
			published
					.setText(FirstScreen.FavoriteList.get(feedValue)._itemlist
							.get(newsValue).getpubDate());
		}

		fontsize = (int) summary.getTextSize();
		Button button1 = (Button) findViewById(R.id.button1);

		button1.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				summary.setTextSize(fontsize + 2);
				fontsize = fontsize + 2;

			}
		});
		Button button2 = (Button) findViewById(R.id.button2);
		button2.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				summary.setTextSize(fontsize - 2);
				fontsize = fontsize - 2;
			}
		});

		
		ImageButton buttonemail = (ImageButton) findViewById(R.id.emailbutton);
		buttonemail.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
				final Intent emailIntent = new Intent(
						android.content.Intent.ACTION_SEND);
				emailIntent.setType("plain/text");
				emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
						new String[] { "" });
				emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
						"ITWeb article - " + text.getText());
				emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
						"http://www.defenceweb.co.za/index.php?option=com_content&view=article&id="+FirstScreen.FavoriteList.get(feedValue)._itemlist.get(
								newsValue).getId().toString());

				startActivity(Intent.createChooser(emailIntent, "Send mail..."));
			}
		});

		ImageButton buttonFav = (ImageButton) findViewById(R.id.favouritesbut);
		if (checkFavorite()) {
			buttonFav.setBackgroundResource(R.drawable.star_black);
			buttonFav.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					Toast.makeText(getApplicationContext(),
							"Already in favourites", Toast.LENGTH_SHORT).show();

				}
			});

		} else {

			buttonFav.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					if (v.getTag() != "CLICKED") {

						if (addFavorite()) {
							Toast.makeText(getApplicationContext(),
									"Added to favourites", Toast.LENGTH_SHORT)
									.show();
							v.setBackgroundResource(R.drawable.star_black);
							v.setTag("CLICKED");
						} else {
							Toast.makeText(
									getApplicationContext(),
									"There has been a mistake, please try again",
									Toast.LENGTH_SHORT).show();
						}

					} else {
						Toast.makeText(getApplicationContext(),
								"Already in favourites", Toast.LENGTH_SHORT)
								.show();
					}
				}
			});

		}

	}

	
	public String determineDensity(){
		switch (getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			density2="ldpi";
			
		    break;
		case DisplayMetrics.DENSITY_MEDIUM:
			density2= "mdpi";
			
			 break;
		case DisplayMetrics.DENSITY_HIGH:
			density2= "hdpi";
			
			 break;
		case DisplayMetrics.DENSITY_XHIGH:
			density2= "xdpi";
			 break;
		}
		return density2;
	}
	public boolean addFavorite() {
		JSONArray JArray;
		try {
			SharedPreferences myPrefs = getSharedPreferences(PREFS_NAME,
					MODE_WORLD_READABLE);
			String prefName = myPrefs.getString("co.za.defenceweb.fav", "title");

			if (prefName.length() > 5) {
				JArray = new JSONArray(prefName);
			} else {
				JArray = new JSONArray();
			}

			JSONObject jObjectType = new JSONObject();

			try {
				jObjectType.put("feed", 1);
				jObjectType.put("id", FirstScreen.FavoriteList
						.get(feedValue)._itemlist.get(newsValue)
						.getId());
				jObjectType.put("title", FirstScreen.FavoriteList
						.get(feedValue)._itemlist.get(newsValue)
						.getTitle());

				JArray.put(jObjectType);
				StringBuilder buf = new StringBuilder();

				buf.append(JArray).append("\n");

				SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.clear();

				// SharedPreferences.Editor editor =
				// getSharedPreferences(MODE_WORLD_READABLE).edit();
				editor.putString("co.za.defenceweb.fav", buf.toString());
				editor.commit();
				return true;
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} catch (JSONException e) {
			e.printStackTrace();

		}
		return false;

	}

	public boolean checkFavorite() {

		try {
			SharedPreferences myPrefs = getSharedPreferences(PREFS_NAME,
					MODE_WORLD_READABLE);
			String prefName = myPrefs.getString("co.za.defenceweb.fav", "title");
			prefName = prefName.replaceAll("/", "");

			JSONArray dat;
			dat = new JSONArray(prefName);

			TextView currentTitle = (TextView) this
					.findViewById(R.id.textarticle);
			for (int t = 0; t < dat.length(); t++) {
				try {
					String obj = dat.getJSONObject(t).getString("title");

					if (obj.equals(currentTitle.getText().toString())) {

						return true;

					}

				} catch (JSONException e) {
					e.printStackTrace();

				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();

		}

		return false;
	}

	private class TweetTask extends AsyncTask<Void, Void, Integer> {
		private SingleFavorite activity;
		ProgressDialog dialog;

		public TweetTask(SingleFavorite activity) {
			this.activity = activity;

		}

		protected void onPreExecute() {
			dialog = new ProgressDialog(activity);
			dialog.setMessage("Tweeting...");
			// dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					tt.cancel(true);
					SingleFavorite.this.finish();
				}
			});
			this.dialog.show();

		}

		@Override
		protected Integer doInBackground(Void... params) {

			SharedPreferences settings = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());

			accessToken = settings.getString("twitter_access_token", null);
			accessTokenSecret = settings.getString(
					"twitter_access_token_secret", null);
			haveNetworkConnection();
			if ((haveConnectedWifi) || (haveConnectedMobile)) {

				if ((accessToken == null) || (accessTokenSecret == null)) {
					mTwitter = new TwitterFactory().getInstance();
					mRequestToken = null;
					mTwitter.setOAuthConsumer(Constants.CONSUMER_KEY,
							Constants.CONSUMER_SECRET);
					String callbackURL = getResources().getString(
							R.string.twitter_callback);
					try {
						mRequestToken = mTwitter
								.getOAuthRequestToken(callbackURL);

						return (Integer) 1;
					} catch (TwitterException e) {
						e.printStackTrace();
					}

				} else {

					return 0;
				}
			} else {

				return 0;
			}

			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
				if (result == 1) {
					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
					startIt();
				}
			}

		}
	}

	public void startIt() {
		Intent i = new Intent(SingleFavorite.this, TwitterWebviewActivity.class);
		i.putExtra("URL", mRequestToken.getAuthenticationURL());
		startActivityForResult(i, TWITTER_AUTH);

	}

	private boolean haveNetworkConnection() {
		haveConnectedWifi = false;
		haveConnectedMobile = false;

		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		for (NetworkInfo ni : netInfo) {
			if (ni.getTypeName().equalsIgnoreCase("WIFI"))
				if (ni.isConnected())
					haveConnectedWifi = true;
			if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
				if (ni.isConnected())
					haveConnectedMobile = true;
		}
		return haveConnectedWifi || haveConnectedMobile;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
		if (requestCode == TWITTER_AUTH) {

			if (resultCode == Activity.RESULT_OK) {

				oauthVerifier = (String) data.getExtras().get("oauth_verifier");
				if (oauthVerifier != null) {
					rt.execute();
				} else {
					tweetB.setBackgroundResource(R.drawable.twitter_visited);
					Toast.makeText(this,
							"There has been a mistake processing your tweet !",
							Toast.LENGTH_SHORT).show();
					if (tt.getStatus() == AsyncTask.Status.RUNNING) {
						tt.dialog.dismiss();
						tt.cancel(true);

					}

					if (rt.getStatus() == AsyncTask.Status.RUNNING) {
						rt.dialog.dismiss();
						rt.cancel(true);

					}
					if (ut.getStatus() == AsyncTask.Status.RUNNING) {
						ut.dialog.dismiss();
						ut.cancel(true);
					}
				}
			} else {
				tweetB.setBackgroundResource(R.drawable.twitter_visited);
				Toast.makeText(this,
						"There has been a mistake processing your tweet !",
						Toast.LENGTH_SHORT).show();
				if (tt.getStatus() == AsyncTask.Status.RUNNING) {
					tt.dialog.dismiss();
					tt.cancel(true);

				}

				if (rt.getStatus() == AsyncTask.Status.RUNNING) {
					rt.dialog.dismiss();
					rt.cancel(true);

				}
				if (ut.getStatus() == AsyncTask.Status.RUNNING) {
					ut.dialog.dismiss();
					ut.cancel(true);
				}

			}

		} else {
			tweetB.setBackgroundResource(R.drawable.twitter_visited);
			Toast.makeText(this,
					"There has been a mistake processing your tweet !", Toast.LENGTH_SHORT)
					.show();

			if (tt.getStatus() == AsyncTask.Status.RUNNING) {
				tt.dialog.dismiss();
				tt.cancel(true);

			}

			if (rt.getStatus() == AsyncTask.Status.RUNNING) {
				rt.dialog.dismiss();
				rt.cancel(true);

			}
			if (ut.getStatus() == AsyncTask.Status.RUNNING) {
				ut.dialog.dismiss();
				ut.cancel(true);
			}

		}

	}

	private class UpdateTask extends AsyncTask<Void, Void, Integer> {

		
		ProgressDialog dialog;
		private SingleFavorite activity;

		protected void onPreExecute() {
			dialog = new ProgressDialog(activity);
			dialog.setMessage("Tweeting...");
			
			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					ut.cancel(true);
					SingleFavorite.this.finish();
				}
			});
			this.dialog.show();

		}

		public UpdateTask(SingleFavorite activity) {
			this.activity = activity;

		}

		@Override
		protected Integer doInBackground(Void... params) {

			SharedPreferences settings = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			accessToken = settings.getString("twitter_access_token", null);
			accessTokenSecret = settings.getString(
					"twitter_access_token_secret", null);
			// Toast.makeText(this, accessToken, 10000).show();
			// Toast.makeText(this, accessTokenSecret, 10000).show();
			haveNetworkConnection();
			if ((haveConnectedWifi) || (haveConnectedMobile)) {
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
				builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
				builder.setOAuthAccessToken(accessToken);
				builder.setOAuthAccessTokenSecret(accessTokenSecret);
				Configuration conf = builder.build();
				Twitter t = new TwitterFactory(conf).getInstance();

				try {

					t.updateStatus(text.getText().toString()
							+ " "
							+ "http://on.itweb.co.za/d/"
							+ FirstScreen.FavoriteList.get(feedValue)._itemlist
									.get(newsValue).getId());

					//
					return (Integer) 1;
				} catch (TwitterException e) {
					e.printStackTrace();
					return 0;

				}
			} else {

				return 0;
			}
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			updateIt(result);

		}
	}

	public void updateIt(Integer result) {
		tweetB.setBackgroundResource(R.drawable.twitter_visited);
		if (result == 1) {
			Toast.makeText(this, "Tweet successfully posted", Toast.LENGTH_SHORT).show();

		} else {
			Toast.makeText(
					this,
					"There has been a mistake...have you already tweeted on this topic?",
					Toast.LENGTH_SHORT).show();
		}

	}

	private class ResumeTask extends AsyncTask<String, Void, Integer> {
		private String oauth;
		ProgressDialog dialog;

		protected void onPreExecute() {
			oauth = oauthVerifier;
			dialog = new ProgressDialog(SingleFavorite.this);
			dialog.setMessage("Tweeting...");
			// dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					rt.cancel(true);
					SingleFavorite.this.finish();
				}
			});
			this.dialog.show();

		}

		public ResumeTask() {

		}

		@Override
		protected Integer doInBackground(String... params) {
			AccessToken at = null;

			try {
				// Pair up our request with the response
				at = mTwitter.getOAuthAccessToken(oauth);
				String theToken = at.getToken();
				// Toast.makeText(this, theToken, 10000).show();
				String theTokenSecret = at.getTokenSecret();
				// Toast.makeText(this, theTokenSecret, 10000).show();
				SharedPreferences settings = PreferenceManager
						.getDefaultSharedPreferences(getApplicationContext());
				settings = PreferenceManager
						.getDefaultSharedPreferences(getApplicationContext());
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("twitter_access_token", theToken);
				editor.putString("twitter_access_token_secret", theTokenSecret);
				editor.commit();
				return (Integer) 1;

				// updateStatus();
			} catch (TwitterException e) {
				e.printStackTrace();
				return 0;
			}
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			if (result == 1) {
				resumeIt();
			}

		}

	}

	public void resumeIt() {
		ut.execute();

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
			if (tt.getStatus() == AsyncTask.Status.RUNNING) {
				tt.dialog.dismiss();
				tt.cancel(true);

			}

			if (rt.getStatus() == AsyncTask.Status.RUNNING) {
				rt.dialog.dismiss();
				rt.cancel(true);

				
			}
			if (ut.getStatus() == AsyncTask.Status.RUNNING) {
				ut.dialog.dismiss();
				ut.cancel(true);
			}
			Intent intent1 = new Intent(SingleFavorite.this, FirstScreen.class);
			intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent1);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBackPressed() {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
		if (tt.getStatus() == AsyncTask.Status.RUNNING) {
			tt.dialog.dismiss();
			tt.cancel(true);

		}

		if (rt.getStatus() == AsyncTask.Status.RUNNING) {
			rt.dialog.dismiss();
			rt.cancel(true);

		}
		if (ut.getStatus() == AsyncTask.Status.RUNNING) {
			ut.dialog.dismiss();
			ut.cancel(true);
		}
		Intent intent1 = new Intent(SingleFavorite.this, FirstScreen.class);
		intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent1);
		finish();

		return;

	}

	@Override
	public void onPause() {
		super.onPause();
		if (tt.getStatus() == AsyncTask.Status.RUNNING) {
			tt.dialog.dismiss();
			tt.cancel(true);

		}

		if (rt.getStatus() == AsyncTask.Status.RUNNING) {
			rt.dialog.dismiss();
			rt.cancel(true);

		}
		if (ut.getStatus() == AsyncTask.Status.RUNNING) {
			ut.dialog.dismiss();
			ut.cancel(true);

		}

	}


}
